namespace RBAC.Read.Api.Application.Handler.BomHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.BomCommand;

    /// <summary>
    /// 产品详情查询处理器（按 Id）
    /// </summary>
    public class GetProductDetailByIdHandler : IRequestHandler<GetProductDetailByIdCommand, APIResult<Product>>
    {
        private readonly IBaseRepository<Product> repository;
        private readonly ILogger<GetProductDetailByIdHandler> logger;

        public GetProductDetailByIdHandler(IBaseRepository<Product> repository, ILogger<GetProductDetailByIdHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        /// <summary>
        /// 处理 按 Id 获取产品详情 请求。
        /// - 校验 Id
        /// - 支持取消
        /// - 区分取消异常与一般异常
        /// - 未找到返回 Fail
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>标准 APIResult</returns>
        public Task<APIResult<Product>> Handle(GetProductDetailByIdCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<Product>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (request.Id <= 0)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "参数错误：Id 必须大于 0";
                    result.Data = null!;
                    return Task.FromResult(result);
                }

                logger.LogInformation("开始获取产品详情 Id={Id}", request.Id);

                var entity = repository.GetModel(request.Id);
                if (entity == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "未找到产品";
                    result.Data = null!;
                    return Task.FromResult(result);
                }

                result.Code = APIEnums.Success;
                result.Msg = "获取产品详情成功";
                result.Data = entity;
            }
            catch (OperationCanceledException)
            {
                logger.LogWarning("获取产品详情被取消, Id={Id}", request.Id);
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.Data = null!;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取产品详情失败: {Message}, Id={Id}", ex.Message, request.Id);
                result.Code = APIEnums.Error;
                result.Msg = "获取产品详情失败";
                result.Data = null!;
            }

            return Task.FromResult(result);
        }
    }
}
